package top.jlzhou.tools.office;

import java.io.File;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

/**
 * 
 * @ClassName	WPS2PdfUtil
 * @Description	TODO(利用wps讲office文档转换成PDF)
 * @author	J.L.Zhou
 * @date	2018年11月29日 下午12:56:14
 * @version	V1.0
 * @Copyright	2018 jlzhou.top Inc. All rights reserved. 
 * 	注意：本内容仅限于公司内部传阅，禁止外泄以及用于其他的商业目
 */
public class WPS2PdfUtil {
	private static final int wdFormatPDF = 17;
    private static final int xlTypePDF = 0;
    private static final int ppSaveAsPDF = 32;


    /**
     * 
     * @Title	convert2PDF   
     * @Description	TODO(判断需要转化文件的类型（Excel、Word、ppt,txt）)   
     * @param inputFile
     * @param pdfFile      
     * @throws	CodeException:
     */
    public static void convert2PDF(String inputFile, String pdfFile) {
        String ext = getFileSufix(inputFile);
        File file = new File(inputFile);
        if (!file.exists()) {
            throw new RuntimeException("文件不存在!");
        }
        if (ext.equals("pdf")) {
           	throw new RuntimeException("原文件就是PDF文件");
        }
        if (ext.equals("doc")||ext.equals("docx")||ext.equals("txt")) {
            word2PDF(inputFile, pdfFile);
        }else if (ext.equals("ppt")||ext.equals("pptx")) {
            ppt2PDF(inputFile, pdfFile);
        }else if(ext.equals("xls")||ext.equals("xlsx")){
            excel2PDF(inputFile, pdfFile);
        }else {
            throw new RuntimeException("不支持的文件类型");
        }
    }

    /***
     * 获取文件后缀
     * @param fileName
     * @return
     */
    public static String getFileSufix(String fileName) {
        int index = fileName.lastIndexOf(".");
        if(index>-1) {
	        return fileName.substring(index + 1).toLowerCase();
	    }else {
	    	return "";
	    }
    }

    /***
     * 
     * Word转PDF
     * 
     * @param inputFile
     * @param pdfFile
     */

    public static void word2PDF(String inputFile, String pdfFile) {
        try {
            // 打开Word应用程序
            ActiveXComponent app = new ActiveXComponent("KWPS.Application");
            // 设置Word不可见
            app.setProperty("Visible", new Variant(false));
            // 禁用宏
            app.setProperty("AutomationSecurity", new Variant(3));
            // 获得Word中所有打开的文档，返回documents对象
            Dispatch docs = app.getProperty("Documents").toDispatch();
            // 调用Documents对象中Open方法打开文档，并返回打开的文档对象Document
            Dispatch doc = Dispatch.call(docs, "Open", inputFile, false, true).toDispatch();
            /***
             * 
             * 调用Document对象的SaveAs方法，将文档保存为pdf格式
             * 
             * Dispatch.call(doc, "SaveAs", pdfFile, wdFormatPDF
             * word保存为pdf格式宏，值为17 )
             * 
             */
            Dispatch.call(doc, "ExportAsFixedFormat", pdfFile, wdFormatPDF);// word保存为pdf格式宏，值为17

            // 关闭文档
            Dispatch.call(doc, "Close", false);
            // 关闭Word应用程序
            app.invoke("Quit", 0);
        } catch (Exception e) {
            throw new RuntimeException("转换Word异常:"+inputFile, e);
        }

    }

    /***
     * 
     * Excel转化成PDF
     * 
     * @param inputFile
     * @param pdfFile
     */
    public static void excel2PDF(String inputFile, String pdfFile) {
        try {

            ComThread.InitSTA(true);
            ActiveXComponent ax = new ActiveXComponent("KET.Application");
            ax.setProperty("Visible", false);
            ax.setProperty("AutomationSecurity", new Variant(3)); // 禁用宏
            Dispatch excels = ax.getProperty("Workbooks").toDispatch();

            Dispatch excel = Dispatch
                    .invoke(excels, "Open", Dispatch.Method,
                            new Object[] { inputFile, new Variant(false), new Variant(false) }, new int[9])
                    .toDispatch();
            // 转换格式
            Dispatch.invoke(excel, "ExportAsFixedFormat", Dispatch.Method, new Object[] { new Variant(0), // PDF格式=0
                    pdfFile, new Variant(xlTypePDF) // 0=标准 (生成的PDF图片不会变模糊) 1=最小文件
                                            // (生成的PDF图片糊的一塌糊涂)
            }, new int[1]);

            // 这里放弃使用SaveAs
            /*
             * Dispatch.invoke(excel,"SaveAs",Dispatch.Method,new Object[]{
             * outFile, new Variant(57), new Variant(false), new Variant(57),
             * new Variant(57), new Variant(false), new Variant(true), new
             * Variant(57), new Variant(true), new Variant(true), new
             * Variant(true) },new int[1]);
             */
            Dispatch.call(excel, "Close", new Variant(false));

            if (ax != null) {
                ax.invoke("Quit", new Variant[] {});
                ax = null;
            }
            ComThread.Release();

        } catch (Exception e) {
           throw new RuntimeException("转换Excel异常："+inputFile, e);
        }
    }
    
    /**
     * 
     * @Title	ppt2PDF   
     * @Description	TODO(ppt转化成PDF)   
     * @param inputFile
     * @param pdfFile      
     * @throws	CodeException:
     */
    public static void ppt2PDF(String inputFile, String pdfFile) {
        try {
            ComThread.InitSTA(true);
            ActiveXComponent app = new ActiveXComponent("KWPP.Application");

            Dispatch ppts = app.getProperty("Presentations").toDispatch();
            Dispatch ppt = Dispatch.call(ppts, "Open", inputFile, true, // ReadOnly
                //    false, // Untitled指定文件是否有标题
                    false// WithWindow指定文件是否可见
            ).toDispatch();
            Dispatch.invoke(ppt, "SaveAs", Dispatch.Method, new Object[]{
                    pdfFile,new Variant(ppSaveAsPDF)},new int[1]);
            System.out.println("PPT");
            Dispatch.call(ppt, "Close");
            app.invoke("Quit");

        } catch (Exception e) {
            throw new RuntimeException("转换PPT异常："+inputFile, e);
        }
    }
}